package com.community.mapper.visitor;

import com.community.entity.Visitor;
import com.community.entity.VisitorDetail;
import com.community.entity.VisitorList;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface VisitorMapper {
//1
    @Insert("INSERT INTO community.visitor (id, houseId, name, gender, mobile, visitDate, userId, status, url, encryptedData) VALUES " +
            "(#{visitor.id}, #{visitor.houseId}, #{visitor.name}, #{visitor.gender}, #{visitor.mobile}, #{visitor.visitDate}, " +
            "#{visitor.userId}, #{visitor.status}, #{visitor.url}, #{visitor.encryptedData})")
    void insertVisitor(@Param("visitor") Visitor visitor);


    @Update("UPDATE community.visitor SET status = #{status} WHERE id = #{id}")
    void modifyStatus(@Param("id") String id, @Param("status") String status);

    @Select("SELECT * FROM community.visitor")
    List<Visitor> getAllVisitors();




//2
    @Select("SELECT COUNT(*) FROM community.visitor WHERE userId = #{userId}")
    int getTotalVisitors(@Param("userId") String userId);


    @Select("SELECT v.id, " +
            "CONCAT(COALESCE(r.point, ''), COALESCE(r.building, ''), COALESCE(r.room, '')) AS houseInfo, " +
            "v.name, v.mobile, v.visitDate, v.status " +
            "FROM community.visitor v " +
            "LEFT JOIN community.room r ON v.houseId = r.id " +
            "WHERE v.userId = #{userId} " +  // 仅查询当前用户的访客记录
            "ORDER BY v.visitDate DESC " +
            "LIMIT #{offset}, #{pageSize}")
    List<VisitorList> getVisitorsWithPagination(
            @Param("offset") int offset,
            @Param("pageSize") int pageSize,
            @Param("userId") String userId);


//3

    @Select("SELECT v.id, " +
            "CONCAT(COALESCE(r.point, ''), COALESCE(r.building, ''), COALESCE(r.room, '')) AS houseInfo, " +
            "v.url, v.visitDate, v.encryptedData " +
            "FROM community.visitor v " +
            "LEFT JOIN community.room r ON v.houseId = r.id " +
            "WHERE v.id = #{id}")
    VisitorDetail getVisitorDetailById(@Param("id") String id);


//4
    @Select("SELECT v.id, " +
            "CONCAT(COALESCE(r.point, ''), COALESCE(r.building, ''), COALESCE(r.room, '')) AS houseInfo, " +
            "v.url, v.visitDate " +
            "FROM community.visitor v " +
            "LEFT JOIN community.room r ON v.houseId = r.id " +
            "WHERE v.encryptedData = #{encryptedData}")
    VisitorDetail getVisitorByEncryptedData(@Param("encryptedData") String encryptedData);

}
